﻿using System.Data;

namespace CavemanTools.Sql
{
	///<summary>
	///</summary>
	public abstract class ParamFactory : IAddDbParameter
	{
		private IDbCommand _cmd;

		internal ParamFactory(IDbCommand cmd)
		{
			_cmd = cmd;
		}


		protected abstract void MapType(IDbDataParameter param, object value);


		protected string Prefix { get; set; }

		/// <summary>
		/// Creates and adds parameter to command
		/// </summary>
		/// <param name="name">Name of param or null for numbered params</param>
		/// <param name="value"></param>
		/// <returns></returns>
		public IDataParameter AddParameter(string name, object value)
		{
			var p = _cmd.CreateParameter();
			if (string.IsNullOrEmpty(name)) name = _cmd.Parameters.Count.ToString();
			p.ParameterName = Prefix + name;
			MapType(p, value);
			_cmd.Parameters.Add(p);
			return p;
		}

		public abstract string FormatParameterName(string name);

		public static IAddDbParameter CreateFactory(IDbCommand cmd, RDBMSType type)
		{
			switch (type)
			{
				default:
					return new SqlServerParamFactory(cmd);
			}
		}
	}
}